import 'package:beamer/beamer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:rabbit_mobile/view/Home/models/home_model.dart';
import 'package:rabbit_mobile/provide/riverpod_notifier.dart';
import 'package:rabbit_mobile/source/language_constant.dart';
import 'package:rabbit_mobile/view/Home/widget/fresh_goods_widget/index.dart';
import 'package:rabbit_mobile/view/Home/widget/home_appbar/index.dart';
import 'package:rabbit_mobile/view/Home/widget/home_category_widget/index.dart';
import 'package:rabbit_mobile/view/Home/widget/hot_Brands_widget/index.dart';
import 'package:rabbit_mobile/view/Home/widget/image_banner_widget/index.dart';
import 'package:rabbit_mobile/view/Home/widget/hotRecommends/index.dart';
import 'package:rabbit_mobile/widget/custom_cache_image_widget/index.dart';
import 'package:rabbit_mobile/widget/price_Widget/index.dart';
import 'package:rabbit_mobile/view/Home/widget/topics_widget/index.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:rabbit_mobile/widget/refresher_widget/index.dart';

class Home extends ConsumerStatefulWidget {
  const Home({super.key});

  @override
  _HomeState createState() => _HomeState();
}

//AutomaticKeepAliveClientMixin: 記錄保存當前頁面的狀態
class _HomeState extends ConsumerState<Home> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  // 重寫wantKeepAlive: 記錄當前的狀態
  @override
  bool get wantKeepAlive => true;

  late TabController _controller;
  late ScrollController _scrollController;
  late RefreshController _refreshController = RefreshController(initialRefresh: false);
  bool show_up = false;

  @override
  void initState() {
    // 获取首页网络数据
    // _loadData();
    super.initState();
    _controller = TabController(length: 0, vsync: this);
    _refreshController = RefreshController();
    _scrollController = ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    _refreshController.dispose();
    _scrollController.dispose();
  }

  void _onLoading() async {
    await Future.delayed(const Duration(milliseconds: 1000));
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    // 記錄狀態
    super.build(context);
    final AsyncValue<HomeModel> homePageImageBannersData = ref.watch(homeProvider);
    double imgWidth = (MediaQuery.of(context).size.width - 68) / 2;

    return NotificationListener(
      // onNotification: 監聽滾動視圖的滾動狀態
      // scrollNotification: 保存滾動試圖的滾動狀態的
      onNotification: (ScrollNotification scrollNotification) {
        // scrollNotification.depth == 0: 表示當前監聽的是首頁的CustomScrollView
        // scrollNotification is ScrollEndNotification: 表示當前的 CustomScrollView 滾動結束了
        if (scrollNotification.depth == 0 && scrollNotification is ScrollEndNotification) {
          if (scrollNotification.metrics.pixels >= MediaQuery.of(context).size.height) {
            show_up = true;
          } else {
            show_up = false;
          }
          setState(() {});
        }
        return true;
      },
      child: Stack(
        children: [
          Scaffold(
            appBar: const HomeAppbar(),
            body: RefresherWidget(
              refreshController: _refreshController,
              enablePullDown: true,
              enablePullUp: false,
              onRefresh: () async {
                await ref.refresh(homeProvider.future);
                _refreshController.refreshCompleted();
              },
              onLoading: _onLoading,
              child: CustomScrollView(
                controller: _scrollController,
                slivers: [
                  SliverToBoxAdapter(
                    child: ImageBannersWidget(
                      imageBannerData: homePageImageBannersData,
                      height: 160.0,
                      type: CustomPaginationBannerType.dot,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: HomeCategoryWidget(
                      categoryData: homePageImageBannersData,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      margin: const EdgeInsets.only(bottom: 20, left: 10, right: 10),
                      padding: const EdgeInsets.fromLTRB(10, 10, 10, 15),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: HotRecommends(
                        hotRecommendsData: homePageImageBannersData,
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: FreshGoodsWidget(
                      freshGoodsdata: homePageImageBannersData,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: HotBrandsWidget(
                      hotBrandsdata: homePageImageBannersData,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: TopicsWidget(topicsData: homePageImageBannersData),
                  ),
                  SliverPersistentHeader(
                    pinned: true, // 設置是否吸頂
                    delegate: CustomSliverPersistentHeaderDelegate(
                      tabBar: _buildTabbarWidget(homePageImageBannersData),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      padding: const EdgeInsets.only(top: 20),
                      margin: const EdgeInsets.only(left: 10, right: 10),
                      height: (imgWidth + 64) * 6,
                      child: TabBarView(
                        controller: _controller,
                        children: _buildCategoryGoodsView(
                          homePageImageBannersData,
                          imgWidth,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          show_up
              ? Positioned(
                  bottom: 50,
                  right: 30,
                  child: GestureDetector(
                    onTap: () {
                      _scrollController.animateTo(0.0, duration: const Duration(milliseconds: 400), curve: Curves.ease);
                    },
                    child: Container(
                      width: 60,
                      height: 60,
                      clipBehavior: Clip.antiAlias,
                      decoration: BoxDecoration(
                        color: const Color.fromRGBO(255, 255, 255, .6),
                        borderRadius: BorderRadius.circular(50),
                      ),
                      child: const Icon(
                        Icons.arrow_circle_up,
                        color: Colors.black,
                        size: 45,
                      ),
                    ),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }

  List<Widget> _tabbarCategoryBanner(List<CategoryBannersModel> data) {
    List<Widget> buildCategoryBanner = [];
    for (var i = 0; i < data.length; i++) {
      CategoryBannersModel categoryBanners = data[i];
      buildCategoryBanner.add(
        Row(
          children: [
            Container(
              padding: EdgeInsets.zero,
              margin: EdgeInsets.zero,
              child: Row(
                mainAxisSize: MainAxisSize.max, // 根据内容最小化宽度
                children: [
                  Container(
                    alignment: Alignment.center,
                    child: Text(
                      homePageLanguage(categoryBanners.name),
                      style: const TextStyle(fontSize: 13.0),
                    ),
                  ),
                ],
              ),
            ),
            if (i != data.length - 1) // 条件判断，避免多余空的 Container
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 10),
                width: 1, // 分隔线宽度
                height: 12, // 分隔线高度
                decoration: const BoxDecoration(
                  color: Color(0xFFC7C7C7), // 分隔线颜色
                ),
              ),
          ],
        ),
      );
    }
    return buildCategoryBanner;
  }

  List<Widget> _buildCategoryGoodsView(AsyncValue data, double imgWidth) {
    List<Widget> buildCategoryGoodsList = [];
    data.when(
      data: (data) {
        for (var i = 0; i < data.categoryBanners.length; i++) {
          buildCategoryGoodsList.add(
            AlignedGridView.count(
              crossAxisCount: 2,
              mainAxisSpacing: 8,
              crossAxisSpacing: 8,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: data.categoryBanners[i].goods.length,
              itemBuilder: (context, index) {
                CategoryBannersGoodsModel CategoryBannersGoodsItem = data.categoryBanners[i].goods[index];
                return Container(
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      GestureDetector(
                        onTap: () {
                          Beamer.of(context).beamToNamed('/goodsDetails/${CategoryBannersGoodsItem.id}');
                        },
                        child: SizedBox(
                          width: imgWidth,
                          height: imgWidth,
                          child: CustomCacheImageWidget(
                            imageUrl: CategoryBannersGoodsItem.picture,
                          ),
                        ),
                      ),
                      const SizedBox(
                        height: 6,
                      ),
                      Text(CategoryBannersGoodsItem.name),
                      const SizedBox(
                        height: 6,
                      ),
                      PriceWidget(price: CategoryBannersGoodsItem.price),
                    ],
                  ),
                );
              },
            ),
          );
        }
      },
      error: (error, StackTrace) {},
      loading: () {},
    );
    return buildCategoryGoodsList;
  }

  TabBar _buildTabbarWidget(AsyncValue data) {
    return data.when(
      data: (data) {
        if (_controller.length != data.categoryBanners.length) {
          // 只有当数据变化时才更新 TabController 的 length
          _controller = TabController(
            length: data.categoryBanners.length,
            vsync: this,
          );
        }
        return TabBar(
          controller: _controller,
          isScrollable: true, // 是否滑動
          unselectedLabelColor: const Color.fromARGB(255, 97, 97, 97), // 未選中的顔色
          indicator: const BoxDecoration(), // 指示器
          labelPadding: EdgeInsets.zero,
          labelColor: Colors.teal,
          tabs: _tabbarCategoryBanner(
            data.categoryBanners,
          ),
        );
      },
      error: (error, StackTrace) {
        return TabBar(
          controller: TabController(length: 0, vsync: this),
          tabs: [],
        );
      },
      loading: () {
        return TabBar(
          controller: TabController(length: 0, vsync: this),
          tabs: [],
        );
      },
    );
  }
}

// 自定義SLiverPersistenHeaderDelegate子類, 構建吸頂視圖
class CustomSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final TabBar? tabBar;
  CustomSliverPersistentHeaderDelegate({this.tabBar});

  // 構建吸頂視圖内容
  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      height: 44.0,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      decoration: BoxDecoration(
        color: shrinkOffset >= 30.0 ? Colors.white : const Color(0xFFF7F7F8),
      ),
      child: tabBar,
    );
  }

  // 吸頂視圖最大高度
  @override
  double get maxExtent => 44.0;

  // 吸頂視圖最小高度
  @override
  double get minExtent => 44.0;

  // 在視圖吸頂的時候, 是否需要重新構建吸頂視圖
  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    // 如果返回true, 表示在視圖吸頂的時候需要重新構建吸頂視圖
    return true;
  }
}
